package com.huawei.csi.tool.util;

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.image.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;

/**
 * @author lxw
 */
public class ResourcesUtil {
    /**
     * LOGGER
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ResourcesUtil.class);

    private ResourcesUtil() {
    }

    /**
     * 绑定资源数据
     */
    public static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("language/language_zn");

    /**
     * 获取对应语言的文本
     */
    public static String message(String key) {
        return RESOURCE_BUNDLE.getString(key);
    }

    /**
     * 从fxml文件加载ui节点
     *
     * @param fxmlName fxmlName
     * @return Parent
     */
    public static Parent loadFXML(String fxmlName) {
        try {
            return FXMLLoader.load(pathToUrl("/fxml/" + fxmlName + ".fxml"), RESOURCE_BUNDLE);
        } catch (IOException e) {
            LOGGER.error("IOException: Load FXML({}) Failed.\t{}", fxmlName, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 文件路径转url地址
     *
     * @param path path
     * @return URL
     */
    public static URL pathToUrl(String path) {
        return ResourcesUtil.class.getResource(path);
    }


    public static String cssExternalForm(String fileName) {
        return toExternalForm("/css/" + replaceFolderSeparator(fileName));
    }

    public static String toExternalForm(String path) {
        return Objects.requireNonNull(ResourcesUtil.class.getResource(path)).toExternalForm();
    }

    public static String imgExternalForm(String fileName) {
        return toExternalForm("/images/" + replaceFolderSeparator(fileName));
    }

    public static List<Image> getIconImages() {
        return List.of(
                new Image(imgExternalForm("/logo/16.png")),
                new Image(imgExternalForm("/logo/32.png")),
                new Image(imgExternalForm("/logo/64.png")),
                new Image(imgExternalForm("/logo/128.png")),
                new Image(imgExternalForm("/logo/256.png"))
        );
    }

    public static String fontExternalForm(String fileName) {
        return toExternalForm("/font/" + replaceFolderSeparator(fileName));
    }

    private static String replaceFolderSeparator(String str) {
        return str.startsWith("/") ? str.substring(1) : str;
    }
}
